<?php

class Nuo_Log_File extends Nuo_Log_Abstract
{
	/**
	 * real path
	 * @var string
	 */
	protected $_path = NULL;

	/**
	 * constructor
	 * @param array $config
	 * @return void
	 */
	function __construct($config)
	{
		$this -> _path = $config['path'] . '/' . date('Y-m-d') . '.log';
		$dir  = dirname($this->_path);
		if(!is_dir($dir))
		{
			@mkdir($dir,0777);	
		}
	}

	/**
	 * write log message
	 * @param string $message
	 * @param string $level
	 * @return Log_File
	 */
	function write($message, $level = Nuo::INFO)
	{
		/**
		 * Delay log write until application shutdown, it's improve site performance
		 */
		if (LOG_DELAY)
		{
			$this -> _data[] = $this -> format($message, $level);
		}
		else
		if ($fp = fopen($this -> _path, 'a+'))
		{
			fwrite($fp, $this -> format($message, $level));
			fclose($fp);
		}
		return $this;
	}

	/**
	 * flush data to storage engine
	 * @return void
	 */
	function flush()
	{
		if ($this -> _data)
		{
			$string = implode(PHP_EOL, $this -> _data);
			if ($fp = fopen($this -> _path, 'a+'))
			{
				fwrite($fp, $string);
				fclose($fp);
				$this -> _data = array();
			}
		}
	}
}
